package com.scm.export;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import org.apache.log4j.Logger;
import com.scm.error.SCPException;
import com.scm.property.PropertyConfig;
import com.scm.property.IPropertyConfig;
import com.snowtide.pdf.OutputTarget;
import com.snowtide.pdf.PDFTextStream;

public class PDFExportImpl implements PDFExport {
	
	private static Logger log = Logger.getLogger(PDFExportImpl.class);
	
	private String filePdf= null;
	private String exportFile = null;
	private String urlPdf = null;
	
	public PDFExportImpl(){
		IPropertyConfig property = new PropertyConfig();
		urlPdf     = property.getStringUrlPdf();
		filePdf    = property.getStringFilePdf();
		exportFile =	property.getStringFileEsport();
		
	}


	public void exportPDFile() throws SCPException{
		
		try {
			if(!existsFile(filePdf)){
				log.info("PDF:"+urlPdf+" Downloading...");
				DownloadSCM.downloadFromUrl(urlPdf,filePdf);
				log.info("Status OK! PDF:"+filePdf);
			}
		} catch (MalformedURLException e) {
			throw new SCPException("URL_DWNLOAD_PDF_FAILED",665,e.getMessage());
		} catch (IOException e) {
			throw new SCPException("DWNLOAD_PDF_FAILED",666,e.getMessage());
		}
		
		if (!existsFile(exportFile)) {
			PDFTextStream pdfts;
			try {
				pdfts = new PDFTextStream(filePdf);
				StringBuilder text = new StringBuilder(1024);
				pdfts.pipe(new OutputTarget(text));
				pdfts.close();
				FileOutputStream file = new FileOutputStream(exportFile);
				PrintStream Output = new PrintStream(file);
				Output.println(text);
			} catch (IOException e) {
				throw new SCPException("FILE_PDF_NOT_FOUND", 555,e.getMessage());
			}
		}
	}
	
	private boolean existsFile(String pathFile){
		File pdfFile = new File(pathFile);
		if(pdfFile.exists()){
			log.debug("File "+pathFile+" Exists!");
			return true;
		}
		return false;
	}

}
